package com.mp.component;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

//这个类是为了实现提供自动填充功能的
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    //当插入时的自动填充
    public void insertFill(MetaObject metaObject) {

        //当有这个createTime字段时再执行，节省开销
        boolean b = metaObject.hasSetter("createTime");

        if(b){
            setInsertFieldValByName("createTime", LocalDateTime.now(), metaObject);
        }
    }

    @Override
    //当更新时的自动填充
    public void updateFill(MetaObject metaObject) {
        //当方法中未设置更新updateTIme值时，val值为空
        //那么就利用这个方法自动填充
        Object val = getFieldValByName("updateTime", metaObject);

        if(val == null){
            setUpdateFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }
    }
}
